<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, onMounted, onBeforeUnmount, nextTick, ref } from 'vue'
import { CurdData, FieldEnum, SchemaConfig } from '@/api/customer/types'
import { useI18n } from '@/hooks/web/useI18n'
import { useValidator } from '@/hooks/web/useValidator'
import useSchema from './hooks/useSchema'
import { FormDialog } from '@/components/Dialog'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { tagsWithInputStore } from '@/store/modules/tagsWithInput'
import { getFieldEnumApi } from '@/api/customer'
import { getSelectListApi as getCountrySelectListApi } from '@/api/regionCountry'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { Selecter, SelectOption } from '@/api/global/types'

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

const { t } = useI18n()

const popDatas = reactive<{ country: Selecter[]; owner: Selecter[]; partner: Selecter[] }>({
  country: [],
  owner: [],
  partner: []
})

// 新增标签start
const tagsWithInputStoreID = 'customerWrite'
const tagsWithInputStoreObj = tagsWithInputStore(tagsWithInputStoreID)
// 新增标签end

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const uploadList = reactive<string[]>([]) // 图片id列表
let fileList: object[] = [] // 图片列表
const { required } = useValidator()
const formDialogSchema = reactive<FormSchema[]>([
  {
    field: 'tags',
    label: t('customer.tags'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  }
])

let countrySelectOptions: SelectOption[] = []
const getCountrySelectList = async () => {
  const res = await getCountrySelectListApi({})
  countrySelectOptions = res.data.list
}

let customerFieldEnum: FieldEnum = {}
const getCustomerFieldEnumList = async () => {
  const res = await getFieldEnumApi({ field: 'all' })
  customerFieldEnum = res.data
}

let operatorOptions: SelectOption[] = []
const getOperatorSelectList = async () => {
  const res = await getOperatorSelectListApi({})
  operatorOptions = res.data.list
}

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const fetchData = async () => {
  await getCountrySelectList()
  await getCustomerFieldEnumList()
  await getOperatorSelectList()

  const schemaConfig: SchemaConfig = {
    fieldEnum: customerFieldEnum,
    formDialogSchema: formDialogSchema,
    tagsWithInputStore: tagsWithInputStoreObj,
    uploadList,
    countrySelectOptions,
    operatorOptions,
    fileList,
    setValues
  }

  const { crudSchemas } = useSchema(schemaConfig)
  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

  // 合并新的数据，确保不改变原有数据的类型
  allSchemas.value = {
    formSchema: newSchemas.formSchema || []
  }
}

fetchData()

const rules: FormRules = reactive({
  // phone: [
  //   { required: true, message: 'Please input your phone number', trigger: 'blur' },
  //   { pattern: /^1[3-9]\d{9}$/, message: '手机号格式有误', trigger: 'blur' }
  // ],
  email: [
    { required: false, message: 'Please input your email address', trigger: 'blur' },
    { type: 'email', message: '邮箱格式有误', trigger: ['blur', 'change'] }
  ]
})

// 提交表单
const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    setValues({
      tags: tagsWithInputStoreObj.tagsList.join(',')
    })
    const formData = await getFormData()

    console.log('formData', formData)

    if (!formData.email && !formData.phone) {
      ElMessage.error('手机号和邮箱需要填写其中一个')
      return Promise.reject('手机号和邮箱需要填写其中一个')
    }
    return formData
  }
}
// 修改页面赋值
watch(
  [() => props.currentRow, () => customerFieldEnum],
  async ([currentRow, customerFieldEnum]) => {
    await nextTick()
    if (!currentRow || !customerFieldEnum) return

    if (currentRow.tags) {
      tagsWithInputStoreObj.tagsList.push(...currentRow.tags.split(','))
    }
    if (currentRow?.att_path_urls) {
      fileList = currentRow?.att_path_urls
    }

    setValues(currentRow)
    await nextTick()
  },
  {
    // deep: true,
    immediate: true
  }
)

// 清空 store 数据
onBeforeUnmount(() => {
  tagsWithInputStoreObj.reset()
})
defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />

  <FormDialog :tagsWithInputStoreID="tagsWithInputStoreID" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
